<template>
  <div class="claim-verification-container">
    <el-page-header :content="title" @back="handleBack" class="page-header" />

    <!-- 错误提示区域 -->
    <el-alert v-if="errorMsg" :message="errorMsg" type="error" show-icon closable @close="errorMsg = ''"
      style="margin-bottom: 16px" />

    <el-card shadow="hover" class="main-card">
      <!-- 1. 待核赔报案列表 -->
      <div v-if="showPendingList">
        <el-table :data="pendingReportList" v-loading="listLoading" border size="small" @row-click="selectPendingReport"
          :row-class-name="tableRowClassName" empty-text="暂无待核赔报案数据">
          <el-table-column prop="reportNo" label="报案号" min-width="180" />
          <el-table-column prop="policyId" label="保单编号" min-width="160" />
          <el-table-column prop="insuredId" label="投保人ID" min-width="120" />
          <el-table-column prop="reporterName" label="报案人" min-width="120" />
          <el-table-column label="灾祸类型" min-width="120">
            <template #default="scope">{{ getDisasterType(scope.row.disasterType) }}</template>
          </el-table-column>
          <el-table-column prop="lossEstimate" label="农户预估损失(元)" min-width="140" align="right">
            <template #default="scope">{{ formatCurrency(scope.row.lossEstimate) }}</template>
          </el-table-column>
          <el-table-column prop="handleTime" label="报案受理时间" min-width="180">
            <template #default="scope">{{ formatDateTime(scope.row.handleTime) }}</template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click="startVerificationByReport(scope.row)"
                :title="!scope.row.hasCalculation ? '该报案暂无关联理算记录，无法发起核赔' : ''">
                处理核赔
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div style="display:flex; justify-content:center; margin-top:12px;">
          <el-pagination background layout="prev, pager, next, jumper, ->, total, sizes"
            :page-size="pagination.pageSize" :current-page="pagination.pageNum" :page-sizes="[5, 10, 20, 50]"
            :total="pagination.total" @size-change="onPageSizeChange" @current-change="onPageChange" />
        </div>
      </div>

      <!-- 2. 核赔处理区域（详情+表单） -->
      <div v-else>
        <!-- 返回列表按钮 -->
        <div style="display:flex; justify-content:flex-end; margin-bottom:15px;">
          <el-button @click="backToPendingList" type="success">返回待核赔列表</el-button>
        </div>

        <!-- 面板批量操作按钮 -->
        <div class="panel-controls" style="margin-bottom: 16px; display: flex; gap: 8px;">
          <el-button type="primary" size="small" @click="toggleAllPanels(true)" :icon="Expand">
            全部展开
          </el-button>
          <el-button type="primary" size="small" @click="toggleAllPanels(false)" :icon="Collapse">
            全部折叠
          </el-button>
        </div>

        <!-- 关联信息展示面板 -->
        <el-collapse class="info-collapse" v-model="activePanels" @change="handlePanelChange">
          <!-- 报案基础信息 -->
          <el-collapse-item title="报案信息" name="report">
            <el-descriptions column="1" border>
              <el-descriptions-item label="报案号">{{ reportInfo.reportNo }}</el-descriptions-item>
              <el-descriptions-item label="保单编号">{{ reportInfo.policyId }}</el-descriptions-item>
              <el-descriptions-item label="投保人ID">{{ reportInfo.insuredId }}</el-descriptions-item>
              <el-descriptions-item label="报案人">{{ reportInfo.reporterName || '无' }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ reportInfo.reporterPhone || '无' }}</el-descriptions-item>
              <el-descriptions-item label="灾祸类型">{{ getDisasterType(reportInfo.disasterType) }}</el-descriptions-item>
              <el-descriptions-item label="灾祸发生时间">{{ formatDateTime(reportInfo.disasterOccurTime)
              }}</el-descriptions-item>
              <el-descriptions-item label="灾祸发生地点">{{ reportInfo.disasterLocation || '无' }}</el-descriptions-item>
              <el-descriptions-item label="损失情况描述">{{ reportInfo.lossDescription || '无' }}</el-descriptions-item>
              <el-descriptions-item label="农户预估损失(元)">{{ formatCurrency(reportInfo.lossEstimate)
              }}</el-descriptions-item>
              <el-descriptions-item label="报案受理时间">{{ formatDateTime(reportInfo.handleTime) }}</el-descriptions-item>
              <el-descriptions-item label="报案状态">
                <el-tag type="warning">{{ getReportStatus(reportInfo.reportStatus) }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <!-- 立案信息 -->
          <el-collapse-item title="立案信息" name="registration" v-if="registrationInfo.registrationId">
            <el-descriptions column="1" border>
              <el-descriptions-item label="立案号">{{ registrationInfo.registrationId }}</el-descriptions-item>
              <el-descriptions-item label="报案号">{{ registrationInfo.reportNo }}</el-descriptions-item>
              <el-descriptions-item label="立案员">{{ registrationInfo.registrarName || registrationInfo.registrarId
              }}</el-descriptions-item>
              <el-descriptions-item label="立案员预估损失(元)">{{ formatCurrency(registrationInfo.surveyorLossEstimate)
              }}</el-descriptions-item>
              <el-descriptions-item label="损失类型">{{ getLossType(registrationInfo.lossType) }}</el-descriptions-item>
              <el-descriptions-item label="损失范围">{{ registrationInfo.lossScope || '无' }}</el-descriptions-item>
              <el-descriptions-item label="是否属于保险责任">
                <el-tag :type="registrationInfo.isCovered === 1 ? 'success' : 'danger'">
                  {{ registrationInfo.isCovered === 1 ? '属于保险责任' : '不属于保险责任' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="责任认定依据">{{ registrationInfo.coverageBasis || '无' }}</el-descriptions-item>
              <el-descriptions-item label="立案时间">{{ formatDateTime(registrationInfo.registrationTime)
              }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
          <div v-else class="empty-info" style="margin: 16px;">
            暂无立案信息（可能该报案尚未完成立案，无法进行核赔）
          </div>

          <!-- 理算信息 -->
          <el-collapse-item title="理算信息" name="calculation" v-if="calculationInfo.calculationId">
            <el-descriptions column="1" border>
              <el-descriptions-item label="理算编号">{{ calculationInfo.calculationId }}</el-descriptions-item>
              <el-descriptions-item label="立案号">{{ calculationInfo.registrationId }}</el-descriptions-item>
              <el-descriptions-item label="理算员">{{ calculationInfo.calculatorName || calculationInfo.calculatorId
              }}</el-descriptions-item>
              <el-descriptions-item label="保单总保额(元)">{{ formatCurrency(calculationInfo.sumInsured)
              }}</el-descriptions-item>
              <el-descriptions-item label="理算核定损失率">{{ (calculationInfo.lossRate).toFixed(2) }}%</el-descriptions-item>
              <el-descriptions-item label="理算核定损失金额(元)">{{ formatCurrency(calculationInfo.lossAmount)
              }}</el-descriptions-item>
              <el-descriptions-item label="理算依据">{{ calculationInfo.calculationBasis || '无' }}</el-descriptions-item>
              <el-descriptions-item label="理算备注">{{ calculationInfo.calculationRemark || '无' }}</el-descriptions-item>
              <el-descriptions-item label="理算状态">
                <el-tag type="success">{{ getCalculationStatus(calculationInfo.calculationStatus) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="理算时间">{{ formatDateTime(calculationInfo.calculationTime)
              }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
          <div v-else class="empty-info" style="margin: 16px;">
            暂无理算信息（可能该立案尚未完成理算，无法进行核赔）
          </div>

          <!-- 保单信息 -->
          <el-collapse-item title="保单信息" name="policy">
            <el-descriptions column="2" border v-if="policyInfo.policyId">
              <el-descriptions-item label="保单编号" span="1">{{ policyInfo.policyId }}</el-descriptions-item>
              <el-descriptions-item label="投保人姓名" span="1">{{ policyInfo.insuredName || policyInfo.insuredId
              }}</el-descriptions-item>
              <el-descriptions-item label="险种名称" span="1">{{ policyInfo.insuranceCoverageName || '无'
              }}</el-descriptions-item>
              <el-descriptions-item label="保险标的" span="1">{{ policyInfo.insuranceSubject || '无'
              }}</el-descriptions-item>
              <el-descriptions-item label="承保面积(亩)" span="1">{{ policyInfo.coverageArea ? `${policyInfo.coverageArea} 亩`
                : '无'
              }}</el-descriptions-item>
              <el-descriptions-item label="承保数量(头/只)" span="1">{{ policyInfo.coverageQuantity ?
                `${policyInfo.coverageQuantity} 头/只` : '无' }}</el-descriptions-item>
              <el-descriptions-item label="单位保额(元)" span="1">{{ formatCurrency(policyInfo.unitInsured)
              }}</el-descriptions-item>
              <el-descriptions-item label="总保额(元)" span="1">{{ formatCurrency(policyInfo.sumInsured)
              }}</el-descriptions-item>
              <el-descriptions-item label="保险费(元)" span="1">{{ formatCurrency(policyInfo.totalPremium)
              }}</el-descriptions-item>
              <el-descriptions-item label="缴费状态" span="1">{{ getPayStatus(policyInfo.payStatus)
              }}</el-descriptions-item>
              <el-descriptions-item label="保险期间" span="1">{{ formatDate(policyInfo.startDate) }} 至 {{
                formatDate(policyInfo.endDate) }}</el-descriptions-item>
              <el-descriptions-item label="保单状态" span="1">
                <el-tag :type="policyInfo.policyStatus === 2 ? 'success' : 'warning'">
                  {{ getPolicyStatus(policyInfo.policyStatus) }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
            <div v-else class="empty-info" style="margin: 16px;">
              暂无保单信息，请检查关联数据是否正确
            </div>
          </el-collapse-item>
        </el-collapse>

        <!-- 核赔表单 -->
        <el-form ref="verificationFormRef" :model="verificationForm" label-width="160px" :rules="formRules"
          class="verification-form" :disabled="formDisabled" style="margin-top: 20px">

          <el-form-item label="报案号" prop="reportNo" required>
            <el-input v-model="verificationForm.reportNo" readonly />
          </el-form-item>

          <el-form-item label="立案号" prop="registrationId" required>
            <el-input v-model="verificationForm.registrationId" readonly />
            <div class="el-form-item__help">
              <span v-if="verificationForm.registrationId" class="text-success">✓ 已获取立案信息</span>
              <span v-else class="text-warning">! 未获取到立案信息，可能导致提交失败</span>
            </div>
          </el-form-item>

          <el-form-item label="理算编号" prop="calculationId" required>
            <el-input v-model="verificationForm.calculationId" readonly />
            <div class="el-form-item__help">
              <span v-if="verificationForm.calculationId" class="text-success">✓ 已获取理算信息</span>
              <span v-else class="text-warning">! 未获取到理算信息，可能导致提交失败</span>
            </div>
          </el-form-item>

          <el-form-item label="保单编号" prop="policyId" required>
            <el-input v-model="verificationForm.policyId" readonly />
          </el-form-item>

          <el-form-item label="投保人ID" prop="insuredId" required>
            <el-input v-model="verificationForm.insuredId" readonly />
          </el-form-item>

          <!-- 核赔员选择 -->
          <el-form-item label="核赔员" prop="verifierId" required>
            <el-select v-model="verificationForm.verifierId" placeholder="请选择核赔员"
              :disabled="formDisabled || !verifierOptions.length" clearable filterable style="width: 100%">
              <el-option v-for="item in verifierOptions" :key="item.workNo" :label="`${item.realName}（${item.workNo}）`"
                :value="item.workNo" />
            </el-select>
          </el-form-item>

          <!-- 基础数据自动填充 -->
          <el-form-item label="理算建议赔付(元)" prop="claimedAmount" required>
            <el-input v-model="verificationForm.claimedAmount" readonly placeholder="自动填充自理算信息" />
          </el-form-item>

          <el-form-item label="保单总保额(元)" prop="policySumInsured" required>
            <el-input v-model="verificationForm.policySumInsured" readonly placeholder="自动填充自保单信息" />
          </el-form-item>

          <el-form-item label="理算核定损失率(%)" prop="lossRate" required>
            <el-input v-model="verificationForm.lossRate" readonly placeholder="自动填充自理算信息（如70%）"
              @change="handleLossRateChange" />
          </el-form-item>

          <!-- 核赔核心操作字段 -->
          <el-form-item label="核赔结果" prop="verificationResult" required>
            <el-select v-model="verificationForm.verificationResult" placeholder="请选择核赔结果" :disabled="formDisabled"
              @change="handleResultChange">
              <el-option label="同意" value="1" />
              <el-option label="调整" value="2" />
              <el-option label="驳回" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item label="调整后赔付金额(元)" prop="adjustedAmount" v-if="verificationForm.verificationResult === '2'"
            required>
            <el-input v-model.number="verificationForm.adjustedAmount" placeholder="请输入调整后的赔付金额"
              :disabled="formDisabled" @input="handleAdjustedAmountChange" @change="handleAdjustedAmountChange"
              type="number" step="0.01" />
          </el-form-item>

          <el-form-item label="最终核定赔付金额(元)" prop="finalPayAmount" required>
            <el-input v-model="verificationForm.finalPayAmount" readonly :disabled="true"
              :style="{ color: verificationForm.verificationResult === '3' ? '#f56c6c' : '#303133' }" />
          </el-form-item>

          <!-- 文本字段 -->
          <el-form-item label="核赔意见" prop="verificationOpinion" required>
            <el-input v-model="verificationForm.verificationOpinion" type="textarea" rows="3"
              placeholder="请填写核赔意见（如：理算符合条款约定，同意赔付；或：损失率核定偏高，建议调整为70%）" :disabled="formDisabled" />
          </el-form-item>

          <el-form-item label="核赔依据" prop="verificationBasis" required>
            <el-input v-model="verificationForm.verificationBasis" type="textarea" rows="2"
              placeholder="请填写核赔依据（如：保单条款第6条、查勘报告第3项、农业保险核赔规范）" :disabled="formDisabled" />
          </el-form-item>

          <el-form-item label="核赔状态" prop="verificationStatus">
            <el-input v-model="verificationForm.verificationStatusText" readonly :disabled="true" />
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item class="form-actions">
            <el-button @click="handleReset" :disabled="formDisabled">重置</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading"
              :disabled="formDisabled || !verificationForm.verifierId || !verificationForm.verificationResult">
              提交核赔
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, computed, onBeforeUnmount, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElNotification, ElLoading, ElMessageBox } from 'element-plus'
import { Expand, Collapse } from '@element-plus/icons-vue'

import axios from 'axios'
import hxxp from '@/utils/hxxp'

// 核心状态变量
const router = useRouter()

// 错误提示
const errorMsg = ref('')

// 页面状态（列表/详情切换）
const title = computed(() => showPendingList.value ? '核赔处理（待核赔报案）' : `核赔处理 - 报案号：${verificationForm.reportNo}`)
const showPendingList = ref(true)
const listLoading = ref(false)
const submitLoading = ref(false)
const formDisabled = ref(true)
const verificationFormRef = ref(null)

// 分页配置
const pagination = reactive({
  pageNum: 1,
  pageSize: 5,
  total: 0
})

// 数据存储
const pendingReportList = ref([]) // 待核赔报案列表
const reportInfo = reactive({}) // 当前选中报案详情
const registrationInfo = reactive({}) // 关联立案信息
const calculationInfo = reactive({}) // 关联理算信息
const policyInfo = reactive({}) // 关联保单信息
const verifierOptions = ref([]) // 核赔员列表

// 面板控制
const panelKeys = ['report', 'registration', 'calculation', 'policy']
const activePanels = ref([]) // 激活的面板

// 核赔表单（修改核赔状态初始值）
const verificationForm = reactive({
  verificationId: '', // 后端生成
  reportNo: '', // 关联报案ID
  calculationId: '', // 关联理算ID
  registrationId: '', // 关联立案ID
  policyId: '', // 关联保单编号
  insuredId: '', // 关联投保人ID
  verifierId: '', // 核赔员ID
  verificationTime: new Date().toISOString(), // 后端覆盖
  claimedAmount: 0.00, // 理算建议赔付金额
  policySumInsured: 0.00, // 保单总保额
  lossRate: 0.00, // 理算损失率（前端显示百分比）
  verificationResult: '', // 核赔结果（1-同意，2-调整，3-驳回）
  adjustedAmount: null, // 调整后金额
  finalPayAmount: 0.00, // 最终赔付金额
  verificationOpinion: '', // 核赔意见
  verificationBasis: '', // 核赔依据
  verificationStatus: null, // 初始状态设为null，提交时根据结果设置
  verificationStatusText: '', // 状态文本初始为空
  _lossRateDecimal: 0.00 // 临时字段：损失率小数格式
})

// 字典映射
const reportStatusMap = {
  1: '待调度',
  2: '待查勘',
  3: '待立案',
  4: '已立案',
  5: '待理算',
  6: '待核赔',
  7: '待结案',
  8: '已结案',
  9: '已驳回'
}
const disasterTypeMap = { 1: '暴雨', 2: '洪水', 3: '病虫害', 4: '疫病', 5: '其他' }
const lossTypeMap = { 1: '部分损失', 2: '全部损失', 3: '死亡损失', 4: '其他损失' }
const calculationStatusMap = { 1: '已理算', 2: '已复核', 3: '已驳回' }
const policyStatusMap = { 1: '待生效', 2: '已生效', 3: '已退保', 4: '已过期' }
const payStatusMap = { 1: '待缴费', 2: '缴费中', 3: '缴费成功', 4: '缴费失败' }

// 字典文本获取函数
const getReportStatus = (value) => reportStatusMap[value] || '未知'
const getDisasterType = (value) => disasterTypeMap[value] || '未知'
const getLossType = (value) => lossTypeMap[value] || '未知'
const getCalculationStatus = (value) => calculationStatusMap[value] || '未知'
const getPolicyStatus = (value) => policyStatusMap[value] || '未知'
const getPayStatus = (value) => payStatusMap[value] || '未知'

// 表单验证规则
const formRules = reactive({
  verificationId: [
    {
      validator: (rule, value, callback) => {
        if (submitLoading.value && !value) callback(new Error('核赔ID生成失败，请重试'))
        else callback()
      },
      trigger: 'blur'
    }
  ],
  reportNo: [
    { required: true, message: '关联报案ID不能为空', trigger: 'blur' }
  ],
  registrationId: [
    { required: true, message: '关联立案ID不能为空', trigger: 'blur' }
  ],
  calculationId: [
    { required: true, message: '关联理算ID不能为空', trigger: 'blur' }
  ],
  policyId: [
    { required: true, message: '关联保单编号不能为空', trigger: 'blur' }
  ],
  insuredId: [
    { required: true, message: '关联投保人ID不能为空', trigger: 'blur' }
  ],
  verifierId: [
    { required: true, message: '请选择核赔员', trigger: 'change' },
    { pattern: /^[A-Za-z0-9]{5,32}$/, message: '核赔员ID为5-32位字母或数字', trigger: 'change' }
  ],
  claimedAmount: [
    { required: true, message: '理算建议赔付金额不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '赔付金额不能为负数', trigger: 'blur' }
  ],
  policySumInsured: [
    { required: true, message: '保单总保额不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '保额不能为负数', trigger: 'blur' }
  ],
  lossRate: [
    { required: true, message: '理算核定损失率不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const num = Number(value)
        if (num < 0 || num > 100) callback(new Error('损失率需在0-100之间（如70%填写70）'))
        else callback()
      },
      trigger: 'blur'
    }
  ],
  verificationResult: [
    { required: true, message: '请选择核赔结果', trigger: 'change' }
  ],
  adjustedAmount: [
    {
      validator: (rule, value, callback) => {
        // 只有在核赔结果为"调整"时才进行必填校验
        if (verificationForm.verificationResult === '2') {
          if (!value && value !== 0) {
            callback(new Error('请输入调整后赔付金额'))
            return
          }
          if (Number(value) < 0) {
            callback(new Error('调整金额不能为负数'))
            return
          }
          if (Number(value) > verificationForm.policySumInsured) {
            callback(new Error(`调整金额不能超过保单总保额（${formatCurrency(verificationForm.policySumInsured)}元）`))
            return
          }
        }
        callback()
      },
      trigger: ['blur', 'change']
    }
  ],
  finalPayAmount: [
    { required: true, message: '最终核定赔付金额不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '最终金额不能为负数', trigger: 'blur' }
  ],
  verificationOpinion: [
    { required: true, message: '请填写核赔意见', trigger: 'blur' },
    { min: 10, message: '核赔意见不少于10个字符', trigger: 'blur' }
  ],
  verificationBasis: [
    { required: true, message: '请填写核赔依据', trigger: 'blur' },
    { min: 8, message: '核赔依据不少于8个字符', trigger: 'blur' }
  ]
})

// 工具函数
const formatCurrency = (value) => {
  if (!value && value !== 0) return '0.00'
  return Number(value).toFixed(2)
}

const formatDateTime = (value) => {
  if (!value) return '未填写'
  return new Date(value).toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit'
  })
}

const formatDate = (value) => {
  if (!value) return '未填写'
  return new Date(value).toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit'
  })
}

const tableRowClassName = ({ row }) => {
  return 'cursor-pointer'
}

const toggleAllPanels = (expand) => {
  activePanels.value = expand
    ? panelKeys.filter(key => {
      if (key === 'registration') return !!registrationInfo.registrationId
      if (key === 'calculation') return !!calculationInfo.calculationId
      return true
    })
    : []
}

const handlePanelChange = (newActive) => {
  activePanels.value = newActive
}

// 数据加载方法
const fetchPendingReports = async () => {
  try {
    listLoading.value = true
    const { pageNum, pageSize } = pagination
    const res = await hxxp.get('/aiClaimReport/all', {
      params: {
        pageNum,
        pageSize,
        reportStatus: 6, // 筛选待核赔状态（6）
        withCalculation: true // 携带是否有关联理算记录标识
      }
    })

    if (res.code === 100200) {
      const pageData = res.data || { list: [], total: 0 }
      pendingReportList.value = Array.isArray(pageData.list)
        ? pageData.list.map(item => ({
          ...item,
          hasCalculation: !!item.calculationId || !!item.hasCalculation
        }))
        : []
      pagination.total = Number(pageData.total || 0)
    } else {
      pendingReportList.value = []
      pagination.total = 0
      ElMessage.error(res.msg || '获取待核赔报案列表失败')
    }
  } catch (e) {
    console.error('获取待核赔列表失败:', e)
    pendingReportList.value = []
    pagination.total = 0
    ElMessage.error('网络异常，获取待核赔报案列表失败')
  } finally {
    listLoading.value = false
  }
}

const getVerifierList = async () => {
  try {
    const res = await hxxp.get('/aiStaffUser/worker', {
      params: { positionCode: 'PTN007' } // 核赔员岗位编码
    })

    if (res.code === 100200) {
      verifierOptions.value = (res.data || []).map(staff => ({
        workNo: staff.workNo,
        realName: staff.realName
      }))
      if (verifierOptions.value.length === 0) {
        ElMessage.warning('当前无可用核赔员，请联系管理员配置')
      }
    } else {
      ElMessage.error(`获取核赔员列表失败：${res.msg || '未知错误'}`)
      verifierOptions.value = []
    }
  } catch (e) {
    console.error('获取核赔员列表失败:', e)
    ElMessage.error('获取核赔员列表失败，请检查网络')
    verifierOptions.value = []
  }
}

const fetchRegistrationByReportNo = async (reportNo) => {
  try {
    const res = await hxxp.get(`/aiClaimRegistration/getByReportNo/${reportNo}`)
    if (res.code === 100200 && res.data) {
      Object.assign(registrationInfo, res.data)
      return true
    } else {
      ElMessage.warning(`报案号${reportNo}未查询到关联立案信息`)
      Object.keys(registrationInfo).forEach(key => registrationInfo[key] = '')
      return false
    }
  } catch (e) {
    console.error('查询立案信息失败:', e)
    ElMessage.error('查询立案信息失败，请重试')
    Object.keys(registrationInfo).forEach(key => registrationInfo[key] = '')
    return false
  }
}

const fetchCalculationByReportNo = async (reportNo) => {
  try {
    const res = await hxxp.get('/aiClaimCalculation/byReportNo', {
      params: { reportNo, calculationStatus: 1 } // 筛选已复核的理算记录
    })
    if (res.code === 100200 && res.data) {
      Object.assign(calculationInfo, res.data)
      if (res.data.calculatorId) {
        const verifier = verifierOptions.value.find(item => item.workNo === res.data.calculatorId)
        calculationInfo.calculatorName = verifier ? verifier.realName : ''
      }
      return true
    } else {
      ElMessage.warning(`报案号${reportNo}未查询到关联理算信息`)
      Object.keys(calculationInfo).forEach(key => calculationInfo[key] = '')
      return false
    }
  } catch (e) {
    console.error('查询理算信息失败:', e)
    ElMessage.error('查询理算信息失败，请重试')
    Object.keys(calculationInfo).forEach(key => calculationInfo[key] = '')
    return false
  }
}

const fetchPolicyByPolicyId = async (policyId) => {
  try {
    const res = await hxxp.get('/aiInsureOrder/getOrder', {
      params: { policyId }
    })
    if (res && res.policyId) {
      Object.assign(policyInfo, res)
      return true
    } else {
      ElMessage.warning(`保单号${policyId}未查询到保单信息`)
      Object.keys(policyInfo).forEach(key => policyInfo[key] = '')
      return false
    }
  } catch (e) {
    console.error('查询保单信息失败:', e)
    ElMessage.error('查询保单信息失败，请重试')
    Object.keys(policyInfo).forEach(key => policyInfo[key] = '')
    return false
  }
}

const fetchReportDetail = async (reportNo) => {
  try {
    const res = await hxxp.get(`/aiClaimReport/${reportNo}`)
    if (res.code === 100200 && res.data) {
      Object.assign(reportInfo, res.data)
      return true
    } else {
      ElMessage.warning(`未查询到报案号${reportNo}的详情`)
      Object.keys(reportInfo).forEach(key => reportInfo[key] = '')
      return false
    }
  } catch (e) {
    console.error('查询报案详情失败:', e)
    ElMessage.error('查询报案详情失败，请重试')
    Object.keys(reportInfo).forEach(key => reportInfo[key] = '')
    return false
  }
}

// 核心业务逻辑
const onPageChange = (page) => {
  pagination.pageNum = page
  fetchPendingReports()
}

const onPageSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  fetchPendingReports()
}

const selectPendingReport = (row) => {
  console.log('选中待核赔报案:', row)
}

const startVerificationByReport = async (row) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载关联数据（报案+立案+理算+保单）...',
    background: 'rgba(255, 255, 255, 0.7)'
  })

  try {
    errorMsg.value = ''
    if (!row?.reportNo || !row?.policyId) {
      throw new Error('报案信息不完整（缺少报案号/保单编号），无法处理核赔')
    }

    // 1. 加载核赔员列表
    await getVerifierList()

    // 2. 加载报案详情
    const reportOk = await fetchReportDetail(row.reportNo)
    if (!reportOk) throw new Error('报案详情加载失败，无法继续')

    // 3. 加载关联立案信息
    const registrationOk = await fetchRegistrationByReportNo(row.reportNo)
    if (!registrationOk) throw new Error('立案信息缺失，无法进行核赔')

    // 4. 加载关联理算信息
    const calculationOk = await fetchCalculationByReportNo(row.reportNo)
    if (!calculationOk) throw new Error('理算信息缺失，无法进行核赔')

    // 5. 加载关联保单信息
    const policyOk = await fetchPolicyByPolicyId(row.policyId)
    if (!policyOk) throw new Error('保单信息缺失，无法进行核赔')

    // 6. 填充核赔表单
    fillVerificationForm(row)

    // 7. 切换视图，展开所有面板
    showPendingList.value = false
    toggleAllPanels(true)
    formDisabled.value = false // 启用表单

  } catch (e) {
    console.error('开始核赔处理失败:', e)
    ElMessage.error(e.message || '加载关联数据失败，请重试')
  } finally {
    loading.close()
  }
}

// 填充核赔表单（初始化状态为空）
const fillVerificationForm = (row) => {
  // 关联ID字段
  verificationForm.reportNo = row.reportNo || ''
  verificationForm.registrationId = registrationInfo.registrationId || ''
  verificationForm.calculationId = calculationInfo.calculationId || ''
  verificationForm.policyId = row.policyId || ''
  verificationForm.insuredId = row.insuredId || ''

  // 基础数据字段
  verificationForm.claimedAmount = calculationInfo.lossAmount || 0.00
  verificationForm.policySumInsured = policyInfo.sumInsured || 0.00
  verificationForm.lossRate = (calculationInfo.lossRate).toFixed(2) || 0.00
  verificationForm._lossRateDecimal = calculationInfo.lossRate || 0.00

  // 初始化可编辑字段（核赔状态初始为空）
  verificationForm.verifierId = ''
  verificationForm.verificationResult = ''
  verificationForm.adjustedAmount = null
  verificationForm.finalPayAmount = 0.00
  verificationForm.verificationOpinion = ''
  verificationForm.verificationBasis = ''
  verificationForm.verificationStatus = null
  verificationForm.verificationStatusText = ''
}

const handleLossRateChange = () => {
  const lossRate = Number(verificationForm.lossRate)
  verificationForm._lossRateDecimal = (lossRate / 100).toFixed(4)
}

// 核赔结果变更时同步设置核赔状态
const handleResultChange = () => {
  switch (verificationForm.verificationResult) {
    case '1': // 同意
      verificationForm.finalPayAmount = verificationForm.claimedAmount
      verificationForm.adjustedAmount = null
      // 同意时设置状态为已核赔
      verificationForm.verificationStatus = 1
      verificationForm.verificationStatusText = '已核赔'
      break
    case '2': // 调整
      verificationForm.finalPayAmount = verificationForm.adjustedAmount || 0.00
      // 调整时也属于已核赔
      verificationForm.verificationStatus = 1
      verificationForm.verificationStatusText = '已核赔'
      break
    case '3': // 驳回
      verificationForm.finalPayAmount = 0.00
      verificationForm.adjustedAmount = null
      // 驳回时设置状态为已拒绝
      verificationForm.verificationStatus = 2
      verificationForm.verificationStatusText = '已拒绝'
      break
    default:
      verificationForm.finalPayAmount = 0.00
      verificationForm.verificationStatus = null
      verificationForm.verificationStatusText = ''
  }
}

const handleAdjustedAmountChange = () => {
  if (verificationForm.verificationResult === '2') {
    const value = Number(verificationForm.adjustedAmount)
    verificationForm.finalPayAmount = isNaN(value) ? 0.00 : value
  }
}

// 提交核赔（确保状态正确设置）
const handleSubmit = async () => {
  if (!verificationFormRef.value) return

  // 表单验证
  try {
    await verificationFormRef.value.validate()
  } catch (error) {
    ElMessage.error('表单验证失败，请检查标红字段')
    return
  }

  // 确保状态已设置
  if (verificationForm.verificationStatus === null) {
    ElMessage.error('请选择核赔结果')
    return
  }

  // 二次确认
  ElMessageBox.confirm(
    verificationForm.verificationResult === '3'
      ? '确定驳回此核赔申请吗？驳回后将终止理赔流程，且无法恢复'
      : '确定提交核赔结果吗？提交后将无法修改',
    '提交确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: verificationForm.verificationResult === '3' ? 'danger' : 'warning',
      closeOnClickModal: false
    }
  ).then(async () => {
    submitLoading.value = true
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交核赔结果...',
      background: 'rgba(255, 255, 255, 0.7)'
    })

    try {
      // 构造提交数据（包含正确的状态）
      const submitData = {
        ...verificationForm,
        lossRate: verificationForm._lossRateDecimal,
        // 提交时使用已设置的状态（1-已核赔，2-已拒绝）
        verificationStatus: verificationForm.verificationStatus,
        verificationStatusText: verificationForm.verificationStatusText
      }
      delete submitData.verificationTime
      delete submitData._lossRateDecimal

      // 调用后端接口
      const res = await hxxp.post('/aiClaimVerification', submitData)

      if (res.code === 100200 && res.data?.verificationId) {
        // 更新前端核赔ID
        verificationForm.verificationId = res.data.verificationId

        // 成功反馈
        const successMsg = verificationForm.verificationStatus === 2
          ? `核赔驳回成功！核赔编号：${verificationForm.verificationId}`
          : `核赔提交成功！核赔编号：${verificationForm.verificationId}，最终赔付：${formatCurrency(verificationForm.finalPayAmount)}元`

        ElMessage.success(successMsg)
        ElNotification({
          title: verificationForm.verificationStatus === 2 ? '核赔已拒绝' : '核赔已完成',
          message: `<p>核赔编号：<strong>${verificationForm.verificationId}</strong></p><p>状态：${verificationForm.verificationStatusText}</p>`,
          type: 'success',
          duration: 5000,
          dangerouslyUseHTMLString: true
        })

        // 3秒后返回列表
        setTimeout(() => {
          backToPendingList()
        }, 3000)

      } else {
        throw new Error(res.msg || '核赔提交失败，未获取核赔编号')
      }

    } catch (e) {
      console.error('提交核赔失败:', e)
      errorMsg.value = `提交失败：${e.message || '网络异常'}`
    } finally {
      submitLoading.value = false
      loading.close()
    }
  }).catch(() => {
    ElMessage.info('已取消核赔提交')
  })
}

const handleReset = () => {
  if (verificationFormRef.value) {
    verificationFormRef.value.resetFields()
  }

  // 保留关联ID和基础数据
  const {
    reportNo,
    registrationId,
    calculationId,
    policyId,
    insuredId,
    claimedAmount,
    policySumInsured,
    lossRate
  } = verificationForm
  fillVerificationForm({ reportNo, policyId, insuredId })
  verificationForm.registrationId = registrationId
  verificationForm.calculationId = calculationId
  verificationForm.claimedAmount = claimedAmount
  verificationForm.policySumInsured = policySumInsured
  verificationForm.lossRate = lossRate
}

const backToPendingList = () => {
  // 重置表单
  Object.keys(verificationForm).forEach(key => {
    if (['claimedAmount', 'policySumInsured', 'lossRate', 'finalPayAmount'].includes(key)) {
      verificationForm[key] = 0.00
    } else if (key === 'adjustedAmount') {
      verificationForm[key] = null
    } else if (key === 'verificationStatus') {
      verificationForm[key] = null
    } else if (key === 'verificationStatusText') {
      verificationForm[key] = ''
    } else {
      verificationForm[key] = ''
    }
  })

  // 重置关联数据
  Object.keys(reportInfo).forEach(key => reportInfo[key] = '')
  Object.keys(registrationInfo).forEach(key => registrationInfo[key] = '')
  Object.keys(calculationInfo).forEach(key => calculationInfo[key] = '')
  Object.keys(policyInfo).forEach(key => policyInfo[key] = '')
  verifierOptions.value = []

  // 切换视图并刷新列表
  showPendingList.value = true
  formDisabled.value = true
  fetchPendingReports()
}

const handleBack = () => {
  router.back()
}

// 监听与初始化
watch(() => verificationForm.verificationResult, (newVal) => {
  handleResultChange()
  if (verificationFormRef.value) {
    // 清除之前的校验错误，但不立即触发新的校验
    verificationFormRef.value.clearValidate('adjustedAmount')
  }
})

watch(() => verificationForm.lossRate, (newVal) => {
  handleLossRateChange()
})

onMounted(() => {
  fetchPendingReports()
})

onBeforeUnmount(() => {
  pendingReportList.value = []
  Object.keys(verificationForm).forEach(key => verificationForm[key] = '')
  Object.keys(reportInfo).forEach(key => reportInfo[key] = '')
  Object.keys(registrationInfo).forEach(key => registrationInfo[key] = '')
  Object.keys(calculationInfo).forEach(key => calculationInfo[key] = '')
  Object.keys(policyInfo).forEach(key => policyInfo[key] = '')
})
</script>

<style scoped>
.claim-verification-container {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #fafafa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;
}

.main-card {
  background-color: #fff;
  padding: 32px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.el-alert {
  margin-bottom: 16px;
}

.el-table {
  margin-bottom: 16px;
}

.el-table__row:hover>td {
  background-color: #f0f7ff !important;
}

.panel-controls {
  padding: 8px 0;
  border-bottom: 1px solid #f1f3f4;
}

.info-collapse {
  margin-bottom: 24px;
  border: 1px solid #f1f3f4;
  border-radius: 8px;
  overflow: hidden;
}

.el-collapse-item__header {
  background-color: #f8f9fa;
  font-weight: 500;
}

.el-collapse-item__content {
  padding: 20px;
}

.empty-info {
  text-align: center;
  padding: 24px;
  color: #606266;
  background-color: #f9fafb;
  border-radius: 8px;
}

.verification-form .el-form-item__help {
  color: #606266;
  font-size: 12px;
  margin-top: 4px;
}

.text-success {
  color: #198754;
}

.text-warning {
  color: #ffc107;
}

.el-form-item {
  margin-bottom: 28px;
}

.form-actions {
  margin-top: 40px;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.el-input__inner[readonly][value^="VERIFY"] {
  color: #1890ff;
  font-weight: 600;
}

@media (max-width: 768px) {
  .claim-verification-container {
    padding: 16px;
  }

  .main-card {
    padding: 16px;
  }

  .el-collapse-item__content {
    padding: 12px;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
